<?php
class Admin extends Model 
{
	protected $table="admin";
	
	public function login()
	{
		$error=true;
		$username=$this->data["username"];
		if(!preg_match("/^[a-zA-Z][\w]{2,15}$/",$username))
		{
			$error="Username Error!";
			return $error;
		}
		if(!class_exists("desencrypt"))
		{
			require("desencrypt.php");
		}
		$des=new Desencrypt();
		$pword=$des->encode($this->data["pword"]);
		$row=$this->find("username='$username' and pword='$pword'");
		if(mysql_num_rows($row)>0)
		{
			$admin=mysql_fetch_assoc($row);
			$_SESSION["admin"]=$row["username"];
			$_SESSION["grade"]=$row["grade"];
			mysql_free_result($row);
			return true;
		}
		else 
		{
			$error="Username or Password Error!";
			return $error;
		}
	}
	
	public function checkInsert()
	{
		$username=$this->data["username"];
		$error=true;
		if(!preg_match("/^[a-zA-Z][\w]{2,15}$/",$username))
		{
			$error="Username Error!";
			return $error;
		}
		if($this->usernameExist())
		{
			$error="Username is exists!";
			return $error;
		}
		if(!class_exists("desencrypt"))
		{
			require("desencrypt.php");
		}
		$des=new Desencrypt();
		$this->data["pword"]=$des->encode($this->data["pword"]);
		return true;
	}
	//如果用户名已经存在则返回false
	public function usernameExist($username="")
	{
		$return=false;
		if(empty($username))
		{
			$username=$this->data["username"];
		}
		$username=$this->find("username='$username'");
		if(mysql_num_rows($username)>0)
		{
			$return=true;			
		}
		mysql_free_result($username);
		return $return;
	}
	
	public function getPword($id_username)
	{
		$pword="";
		if(is_int($id_username))
		{
			$admin="id=$id_username";
		}
		else 
		{
			$admin="username='$id_username'";
		}
		$admin=$this->find($admin);
		if($row=mysql_fetch_assoc($admin))
		{
			if(!class_exists("desencrypt"))
			{
				require("desencrypt.php");
			}
			$des=new Desencrypt();
			$pword=$des->decode($row["pword"]);
		}
		mysql_free_result($admin);
		return $pword;
	}
}